package com.yyge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyge.common.enums.AckCode;
import com.yyge.common.exception.ServiceException;
import com.yyge.common.util.WaimaiThreadLocal;
import com.yyge.controller.mobile.cart.req.MobileCartAddReq;
import com.yyge.controller.mobile.cart.req.MobileAddCartNumReq;
import com.yyge.controller.mobile.cart.resp.MobileCartResp;
import com.yyge.controller.mobile.login.resp.MobileLoginResp;
import com.yyge.controller.mobile.mapstruct.MobileCartConvert;
import com.yyge.entity.Product;
import com.yyge.entity.ShoppingCart;
import com.yyge.mapper.ProductMapper;
import com.yyge.mapper.ShoppingCartMapper;
import com.yyge.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
* @author Administrator
* @description 针对表【shopping_cart(购物车)】的数据库操作Service实现
* @createDate 2023-07-02 20:36:22
*/
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
    implements ShoppingCartService{

    @Autowired
    private ProductMapper productMapper;


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<MobileCartResp> findByMerchantId(Long id) {
        MobileLoginResp mobileLoginResp= WaimaiThreadLocal.mobileLoginThreadLocal.get();

        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        //哪一个商家
        queryWrapper.eq(ShoppingCart::getMerchantId,id);
        //当前用户id
        queryWrapper.eq(ShoppingCart::getUserId,mobileLoginResp.getId());

        List<ShoppingCart> shoppingCartList = super.list(queryWrapper);
        // 转换对象

        return MobileCartConvert.MAPPER.convert(shoppingCartList);
    }

    /**
     * 首次产品加入购物车
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer cartAdd(MobileCartAddReq req) {
       //得到数据库商品(加悲观锁)
        Product db = this.productMapper.pessimisticLockById(req.getDishId());
        System.out.println("获得数据库的商品");
        System.out.println(db);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

         //商品下架
        if(db.getIsgrounding().equals("0")){
            throw new ServiceException(AckCode.PRODUCT_DELISTING);
        }

        //有限量,判断库存够不够
        if(db.getNum()!=-1){
            //库存不够
            if(db.getNum()-1<=0){
                throw new ServiceException(AckCode.PRODUCT_STORE_EMPTY);
            }
            //减1个库存
            //this.productMapper.descNum(req.getDishId(),1);
        }

        //加入购物车(可以redis 来实现  hash数据类型)
        ShoppingCart shoppingCart = MobileCartConvert.MAPPER.convert(req);
        shoppingCart.setNumber(1);

        //谁买的
        Integer userId=WaimaiThreadLocal.mobileLoginThreadLocal.get().getId();
        System.out.println("USERID有对象么");
        System.out.println(WaimaiThreadLocal.mobileLoginThreadLocal.get());
        shoppingCart.setUserId(new Long(userId));
        //向购物车中添加数据
        super.save(shoppingCart);

        return  shoppingCart.getNumber();
    }


   /**
     * 向已有购物车中添加数量
     * @param req
     * @return
     */
    @Override
    public Integer addCarNumApi(MobileAddCartNumReq req) {
        //得到数据库商品(加悲观锁)
        Product db = this.productMapper.pessimisticLockById(req.getDishId());
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //商品下架
        if(db.getIsgrounding().equals("0")){
            throw new ServiceException(AckCode.PRODUCT_DELISTING);
        }

        //有限量,判断库存够不够
        if(db.getNum()!=-1){
            //库存不够
            if(db.getNum()-1<=0){
                throw new ServiceException(AckCode.PRODUCT_STORE_EMPTY);
            }
            //减1个库存
           // this.productMapper.descNum(req.getDishId(),1);
        }

        //谁买的
        Integer userId=WaimaiThreadLocal.mobileLoginThreadLocal.get().getId();

        //查询购物车中的数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getMerchantId,req.getMerchantId());
        queryWrapper.eq(ShoppingCart::getDishId,req.getDishId());
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        ShoppingCart  shoppingCartDb=this.shoppingCartMapper.selectOne(queryWrapper);

        //没有数据,要回滚
        if(Objects.isNull(shoppingCartDb)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //更新购物车的数量
        shoppingCartDb.setNumber(shoppingCartDb.getNumber()+1);
        this.shoppingCartMapper.updateById(shoppingCartDb);

        //返回最新的数量
        return shoppingCartDb.getNumber();
    }

    @Override
    public Integer subCarNumApi(Long id) {

        //谁买的
        Integer userId=WaimaiThreadLocal.mobileLoginThreadLocal.get().getId();

        //查询购物车中的数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getDishId,id);
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        ShoppingCart  shoppingCartDb=this.shoppingCartMapper.selectOne(queryWrapper);

        //没有数据,要回滚
        if(Objects.isNull(shoppingCartDb)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //更新购物车的数量
        if(shoppingCartDb.getNumber()-1<0){
            throw new ServiceException(AckCode.DATABASE_ERROR);
        }
        shoppingCartDb.setNumber(shoppingCartDb.getNumber()-1);
        this.shoppingCartMapper.updateById(shoppingCartDb);

        //返回最新的数量
        return shoppingCartDb.getNumber();
    }


    /**
     * 清空自己某个商家的购物车数据
     * @param merchantId
     * @return
     */
    @Override
    public boolean cleanCart(Long merchantId) {
        //谁买的
        Integer userId=WaimaiThreadLocal.mobileLoginThreadLocal.get().getId();
        //查询购物车中的数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getMerchantId,merchantId);
        queryWrapper.eq(ShoppingCart::getUserId,userId);

        this.shoppingCartMapper.delete(queryWrapper);
        return true;
    }
}




